var express = require('express')
var sha1 = require('sha1')
var superagent = require('superagent')
var router = express.Router()

/* GET home page. */
router.get('/', function (req, res, next) {
	let { signature, timestamp, nonce, echostr } = req.query
	let token = 123456
	let tmpArr = [token, timestamp, nonce]
	tmpArr.sort()
	let tmpStr = tmpArr.join('')
	tmpStr = sha1(tmpStr)
	if (tmpStr == signature) {
		res.send(echostr)
	} else {
		res.json(false)
	}
})

router.post('/', function (req, res, next) {
	let { body } = req
	let media_id = 'p4XjGi8nKmmGisZWtpNlw-lBXhGHNOy_4RbUUqyin41Yl22DKP4R0SkpzpQB7nuh'
	console.log('用户信息：' + JSON.stringify(body))
	if (body.MsgType === 'text') {
		if (body.Content === '小程序') {
			return send({ touser: body.FromUserName, msgtype: 'text', text: { content: '<a href="http://www.qq.com" data-miniprogram-appid="wxf615f25bab7cbd94" data-miniprogram-path="pages/index/index">点击跳小程序进入首页</a>' } })
		}
		if (body.Content === '图片') {
			return send({ touser: body.FromUserName, msgtype: 'image', image: { media_id } })
		} if (body.Content === '图文链接') {
			return send({ touser: body.FromUserName, msgtype: 'link', link: { title: '标题', description: '消息', url: 'http://www.qq.com', thumb_url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.juimg.com%2Ftuku%2Fyulantu%2F140703%2F330746-140F301555752.jpg&refer=http%3A%2F%2Fimg.juimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620524263&t=96de9f7dc03c6fd1f7e52e9c00bcd95b' } })
		} if (body.Content === '小程序卡片') {
			return send({ touser: body.FromUserName, msgtype: 'miniprogrampage', miniprogrampage: { title: '标题', pagepath: 'pages/index/index', thumb_media_id: media_id } })
		}
		send({ touser: body.FromUserName, msgtype: 'text', text: { content: body.Content } })
	}
	else if (body.MsgType === 'miniprogrampage') {
		if (body.Title) {
			send({ touser: body.FromUserName, msgtype: 'text', text: { content: '欢迎进群' } })

		}
	}
	res.json(req.body)
})

async function getAccessToken() {
	let appid = 'wxf615f25bab7cbd94'
	let secret = '5dcd000fa1a0d045fc11de5847266113'
	return new Promise((resolve, reject) => {
		superagent.post(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`).end((err, res) => {
			if (err) {
				reject(err)
			}
			resolve(res.body.access_token)
		})
	})
}

async function send({ touser, msgtype, text, image, link, miniprogrampage }) {
	let access_token = await getAccessToken()
	console.log(access_token)
	superagent.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${access_token}`).send({ touser, msgtype, text, image, link, miniprogrampage }).end((err, res) => {
		if (err) {
			return
		}
		console.log(res.body)
	})
}

module.exports = router
